package com.itfreer.data.query;

import java.util.List;
import java.util.Map;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.itfreer.data.db.dao.DBRegistDao;
import com.itfreer.data.db.dao.DataDao;
import com.itfreer.data.db.entity.DBRegistEntity;

@Component
public class JdbcDataDaoImp implements DataDao {
	
	@Autowired 
	protected DBRegistDao dbrRegistDao;
	
	@SuppressWarnings({ "unchecked", "deprecation" })
	@Override
	public List<Map<String,Object>> getRows(String id, String queryFields,String queryWhere,
			String order, Integer pageSize, Integer pageIndex) {
		//获取数据库注册实体对象
		DBRegistEntity dbentity = dbrRegistDao.getEntity(id);
		if(dbentity == null){
			return null;
		}
		try {
			//获取session对象
			Session session = HibernateDataUtils.getOpenSession(dbentity);
			Transaction tx = session.beginTransaction();
			String sql = HibernateDataUtils.toSelectSql(dbentity, queryFields, queryWhere, order);
			//默认从0 开始，即第一条记录
			int startIndex = 0;
			
			if(pageSize <= 0){
				//默认每次查询1000条
				pageSize = 1000;
			}
			
			if(pageIndex >= 1) {
				startIndex = pageSize * (pageIndex - 1);
			}
			
			List<Map<String, Object>> list =HibernateDataUtils.toUpper(session.createNativeQuery(sql).setFirstResult(startIndex).setMaxResults(pageSize).
					setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list());
			tx.commit();
			session.close();
			return list;
		} catch (HibernateException e) {
			// TODO: handle exception
			e.printStackTrace();
			return null;
		}
		
	}

	@SuppressWarnings("unchecked")
	@Override
	public Long getRowCounts(String id, String queryWhere) {
		DBRegistEntity dbentity = dbrRegistDao.getEntity(id);
		if(dbentity == null){
			return null;
		}
		
		try {
			//获取session对象
			Session session = HibernateDataUtils.getOpenSession(dbentity);
			Transaction tx = session.beginTransaction();
			String sql = HibernateDataUtils.toCountSql(dbentity,queryWhere);
			List<Object> list =session.createNativeQuery(sql).list();
			Long count = Long.parseLong(list.get(0).toString());
			tx.commit();
			session.close();
			return count;
		} catch (HibernateException e) {
			// TODO: handle exception
			e.printStackTrace();
			return null;
		}
	}

}
